<template>
  <div class="app-container">
    <!-- 头部 -->
    <div class="header">
      <h1>金料调拨审核</h1>
      <p>审核调拨和派发申请</p>
    </div>

    <div class="main-content">
      <!-- 搜索筛选 -->
      <div class="search-section">
        <el-form :model="queryForm" inline>
          <el-form-item label="调拨单号">
            <el-input v-model="queryForm.transferNo" placeholder="请输入调拨单号" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadData">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <el-table v-loading="loading" :data="tableData" stripe style="width: 100%">
          <el-table-column prop="transferNo" label="调拨单号" width="150" />
          <el-table-column prop="transferType" label="单据类型" width="100">
            <template #default="{ row }">
              <el-tag :type="row.transferType === 1 ? 'primary' : 'success'">
                {{ row.transferType === 1 ? '调拨' : '派发' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="fromWarehouseName" label="调出仓库" width="120">
            <template #default="{ row }">
              {{ row.fromWarehouseName || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="toWarehouseName" label="调入仓库" width="120">
            <template #default="{ row }">
              {{ row.toWarehouseName || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="transferWeight" label="调拨克重" width="120">
            <template #default="{ row }"> {{ row.transferWeight }}克 </template>
          </el-table-column>
          <el-table-column prop="transferReason" label="调拨原因" min-width="150" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="approveRemark" label="审核备注" width="150">
            <template #default="{ row }">
              {{ row.approveRemark || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="attachmentUrl" label="附件" width="100">
            <template #default="{ row }">
              <span v-if="row.attachmentUrl" class="attachment-link">
                <a :href="row.attachmentUrl" target="_blank" class="detail-link">查看附件</a>
              </span>
              <span v-else class="attachment-empty">空</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="申请时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="approverName" label="审批人" width="100" />
          <el-table-column prop="approveTime" label="审批时间" width="160">
            <template #default="{ row }">
              {{ row.approveTime ? formatDateTime(row.approveTime) : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="row.status === 0"
                type="success"
                size="small"
                :disabled="approving"
                @click="approveTransfer(row, 1)"
              >
                通过
              </el-button>
              <el-button
                v-if="row.status === 0"
                type="danger"
                size="small"
                :disabled="approving"
                @click="approveTransfer(row, 2)"
              >
                拒绝
              </el-button>
              <el-button
                type="primary"
                size="small"
                :disabled="viewingDetail"
                @click="viewDetail(row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            :current-page="queryForm.pageNo"
            :page-size="queryForm.pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="loadData"
            @current-change="loadData"
          />
        </div>
      </div>
    </div>

    <!-- 审核弹窗 -->
    <el-dialog
      v-model="approveDialogVisible"
      :title="approveForm.decision === 1 ? '通过审核' : '拒绝审核'"
      width="500px"
    >
      <el-form :model="approveForm" label-width="100px">
        <el-form-item label="调拨单号">
          <el-input v-model="approveForm.transferNo" disabled />
        </el-form-item>
        <el-form-item label="调拨克重">
          <el-input v-model="approveForm.transferWeight" disabled />
        </el-form-item>
        <el-form-item label="审批备注">
          <el-input
            v-model="approveForm.approveRemark"
            type="textarea"
            :rows="3"
            :placeholder="approveForm.decision === 1 ? '请输入通过原因' : '请输入拒绝原因'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button
          :type="approveForm.decision === 1 ? 'success' : 'danger'"
          :loading="approving"
          @click="submitApprove"
        >
          {{ approveForm.decision === 1 ? '确认通过' : '确认拒绝' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="调拨详情" width="600px">
      <div v-if="currentTransfer" class="transfer-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="调拨单号">
            {{ currentTransfer.transferNo }}
          </el-descriptions-item>
          <el-descriptions-item label="单据类型">
            <el-tag :type="currentTransfer.transferType === 1 ? 'primary' : 'success'">
              {{ currentTransfer.transferType === 1 ? '调拨' : '派发' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="调出仓库">
            {{ currentTransfer.fromWarehouseName }}
          </el-descriptions-item>
          <el-descriptions-item label="调入仓库">
            {{ currentTransfer.toWarehouseName }}
          </el-descriptions-item>
          <el-descriptions-item label="调拨克重">
            {{ currentTransfer.transferWeight }}克
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentTransfer.status)">
              {{ getStatusText(currentTransfer.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="调拨原因" :span="2">
            {{ currentTransfer.transferReason || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="申请人">
            {{ currentTransfer.creatorName }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ formatDateTime(currentTransfer.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentTransfer.approverName" label="审批人">
            {{ currentTransfer.approverName }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentTransfer.approveTime" label="审批时间">
            {{ formatDateTime(currentTransfer.approveTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="审批备注" :span="2">
            {{ currentTransfer.approveRemark || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="附件" :span="2">
            <span v-if="currentTransfer.attachmentUrl" class="attachment-link">
              <a :href="currentTransfer.attachmentUrl" target="_blank" class="detail-link"
                >查看附件</a
              >
            </span>
            <span v-else class="attachment-empty">无</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getTransferPage,
  approveTransfer as approveTransferApi,
  getTransfer
} from '../../../api/gold/transfer'

// 用于路由缓存（keep-alive）与菜单"组件名称"一致
defineOptions({ name: 'GoldTransferAudit' })

// 查询表单
const queryForm = reactive({
  pageNo: 1,
  pageSize: 10,
  transferNo: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref<any[]>([])
const total = ref(0)

// 防连点状态
const approving = ref(false) // 审核提交状态
const viewingDetail = ref(false) // 详情查看状态

// 审核弹窗
const approveDialogVisible = ref(false)
const approveForm = reactive({
  id: 0,
  transferNo: '',
  transferWeight: '',
  decision: 1, // 1-通过 2-拒绝
  approveRemark: ''
})

// 详情弹窗
const detailDialogVisible = ref(false)
const currentTransfer = ref<any>(null)

// 格式化时间
const formatDateTime = (date?: any) => {
  if (!date) return '-'
  const d = new Date(date)
  return d
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}

// 获取状态类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0:
      return 'warning'
    case 1:
      return 'success'
    case 2:
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '待确认'
    case 1:
      return '已确认'
    case 2:
      return '已拒绝'
    default:
      return '未知'
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const result = (await getTransferPage(queryForm)) as any
    let data = result?.data || result

    if (data && data.list) {
      tableData.value = data.list
      total.value = data.total || 0
    } else {
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryForm.transferNo = ''
  queryForm.pageNo = 1
  loadData()
}

// 审核调拨
const approveTransfer = (row: any, decision: number) => {
  approveForm.id = row.id
  approveForm.transferNo = row.transferNo
  approveForm.transferWeight = row.transferWeight + '克'
  approveForm.decision = decision
  approveForm.approveRemark = ''
  approveDialogVisible.value = true
}

// 提交审核
const submitApprove = async () => {
  // 防连点：如果正在审核，直接返回
  if (approving.value) {
    return
  }

  try {
    approving.value = true
    await approveTransferApi({
      id: approveForm.id,
      decision: approveForm.decision,
      approveRemark: approveForm.approveRemark
    })

    ElMessage.success(approveForm.decision === 1 ? '审核通过' : '审核拒绝')
    approveDialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('审核失败:', error)
    ElMessage.error('审核失败')
  } finally {
    approving.value = false
  }
}

// 查看详情
const viewDetail = async (row: any) => {
  // 防连点：如果正在查看详情，直接返回
  if (viewingDetail.value) {
    return
  }

  try {
    viewingDetail.value = true
    const result = (await getTransfer(row.id)) as any
    let data = result?.data || result

    if (data) {
      currentTransfer.value = data
      detailDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  } finally {
    viewingDetail.value = false
  }
}

// 页面挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.app-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: white;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header h1 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
}

.header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.main-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.transfer-detail {
  padding: 10px 0;
}

.attachment-link {
  min-width: 60px;
  text-align: left;
}

.attachment-empty {
  min-width: 60px;
  text-align: left;
}

.detail-link {
  color: #409eff;
  text-decoration: none;
}

.detail-link:hover {
  text-decoration: underline;
}
</style>
